﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using VitCode.Castle.Entities;
using VitCode.Castle.Helper;

namespace VitCode.Castle.DataAccess
{
    public class CastleAccess : BaseDataAccess
    {
         
        public  bool SaveOrUpdateObj(object obj)
        {
            try
            {
                BeginTransaction();
                SaveOrUpdate(obj);
                Commit();
                return true;
            }
            catch (Exception ex)
            {
                RollBack();
                return false;
            }
            finally
            {
                CloseSession();
            }
        }

        public  bool DeleteObj(object obj)
        {
            try
            {
                BeginTransaction();
                Delete(obj);
                Commit();
                return true;
            }
            catch (Exception ex)
            {
                RollBack();
                return false;

            }
            finally
            {
                CloseSession();
            }

        }



        public IList CheckExist(string hql)
        {
            return Session.CreateQuery(hql).List();
        }

        /// <summary>
        /// 用戶驗證
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public User CheckLogin(string userCode, string pwd)
        {
            var nvc = new NameValueCollection();
            nvc.Add("Code", userCode);
            nvc.Add("Password", pwd);
            IList list = GetObjectList((new User()).GetType().Name, nvc);
            if (list != null && list.Count == 1 && list[0] is User)
            {
                return (User)list[0];
            }
            return null;
        }

        /// <summary>
        /// 根據用戶編號獲取用戶物件
        /// </summary>
        /// <param name="strCode">用戶編號</param>
        /// <returns></returns>
        public User GetUserByCode(string strCode)
        {
            var nvc = new NameValueCollection {{"Code", strCode}};
            IList list = GetObjectList((new User()).GetType().Name, nvc);
            if (list != null && list.Count == 1 && list[0] is User)
            {
                return (User)list[0];
            }
            return null;
        }

        /// <summary>
        /// 根據用戶ID獲取用戶物件
        /// </summary>
        /// <param name="id">用戶ID</param>
        /// <returns></returns>
        public User GetUser(Guid id)
        {
            User reVal = (User)(Session.Load(new User().GetType().Name, id));
            return reVal;
        }

        /// <summary>
        /// 獲取用戶所擁有的資源
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public NameObjectDictionary GetUserResourceSet(string userCode)
        {
            var nd = new NameObjectDictionary();

            return nd;
        }

        public bool CheckIsAdmin(string userId)
        {
            var dt0 = GetDataTableBySql("select Code from dbo.Frame_User where Id='" + userId + "'");
            if(dt0 != null && dt0.Rows.Count > 0)
            {
                var code = dt0.Rows[0]["Code"].ToString();
                if (code == "admin") return true;
            }
            var dt =
                  GetDataTableBySql("select Alias from dbo.Frame_Role frole join dbo.Frame_User_Role fur on frole.Id = fur.RoleId join dbo.Frame_User fu on fu.Id = fur.UserId where fu.Id ='" +userId + "'");
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var roleAlias = dt.Rows[i][0].ToString();
                    if (roleAlias == "admin")
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 通过用户ID获取用户所有权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>权限对象集合</returns>
        public IList GetRolesbyUserId(string userId)
        {
            var lst =
                Session.CreateQuery(
                    "From Role c Where c.Id in (Select ur.RoleId From UserRoleRelation ur Where ur.UserId='"+userId+"') ").List();
            return lst;
        }

        /// <summary>
        /// 通过用户ID获取用户所有权限(出字符串形式呈现)
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户所有权限(出字符串形式呈现)</returns>
        public string GetUserRolesStringByUserId(string userId)
        {
            var lst = GetRolesbyUserId(userId);
            var sb = new StringBuilder();
            if(lst!=null)
            {
                for(var i=0;i<lst.Count;i++)
                {
                    if(lst[i] is Role)
                    {
                        sb.Append(((Role) lst[i]).Alias);
                    }
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 加密狗检测
        /// </summary>
        /// <returns></returns>
        public static bool CheckDogKeys()
        {
            var dog = new Dog(100) { DogAddr = 0, DogBytes = 10 };
            var r = new Random(1000);
            int Retcode = dog.ReadDog();
            if (Retcode == 0)
            {
                return true;
            }
             return false;
            
        }
    }
}
